/*
 * Copyright (C) 2009 Jakub Miara
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.araim;

import android.graphics.drawable.Drawable;
import android.graphics.drawable.TransitionDrawable;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

public class BackgroundAnimation extends TransitionDrawable {

	public BackgroundAnimation(Drawable[] ds, View v, int interval, View[] touchListenersToSet) {
		super(ds);
		v.setBackgroundDrawable(this);
		sDrawable = getDrawable(0);
		eDrawable = getDrawable(1);
		animationInterval = interval;
		initVars();

		if (touchListenersToSet != null) {
			BackgroundAnimationTouchListener batl = new BackgroundAnimationTouchListener();
			for (View vv : touchListenersToSet) {
				vv.setOnTouchListener(batl);
			}
		}
	}

	private void initVars() {
		setCrossFadeEnabled(true);
		setId(0, 0);
		setId(1, 1);
	}

	public void blink() {
		start();
		revert();
	}

	public void start() {
		setDrawableByLayerId(0, sDrawable);
		setDrawableByLayerId(1, eDrawable);
		startTransition(animationInterval);
	}

	public void revert() {
		setDrawableByLayerId(0, eDrawable);
		setDrawableByLayerId(1, sDrawable);
		startTransition(animationInterval);
	}

	protected int animationInterval;
	protected Drawable sDrawable = null;
	protected Drawable eDrawable = null;

	private class BackgroundAnimationTouchListener implements OnTouchListener {

		public boolean onTouch(View v, MotionEvent event) {
			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				BackgroundAnimation.this.start();
			} else if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL
					|| event.getAction() == MotionEvent.ACTION_OUTSIDE) {
				BackgroundAnimation.this.revert();
			}
			return false;
		}

	}
}
